package com.superMall.service.impl;

import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import com.superMall.common.Const;
import com.superMall.common.ResponseCode;
import com.superMall.common.ServerResponse;
import com.superMall.dao.CartMapper;
import com.superMall.dao.ProductMapper;
import com.superMall.pojo.Cart;
import com.superMall.pojo.Product;
import com.superMall.service.ICartService;
import com.superMall.util.BigDecimalUtil;
import com.superMall.util.PropertiesUtil;
import com.superMall.vo.CartProductVO;
import com.superMall.vo.CartVO;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

/**
 * Created by guanwei on 2017/11/21.
 */
@Service("iCartService")
public class CartServiceImpl implements ICartService {

    @Autowired
    private CartMapper cartMapper;

    @Autowired
    private ProductMapper productMapper;

    public ServerResponse<CartVO> add(Integer userId,Integer productId, Integer count){
        if(productId == null || count == null){
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(),ResponseCode.ILLEGAL_ARGUMENT.getDesc());
        }
        Cart cart = cartMapper.selectByUserIdAndProductId(userId, productId);
        int rowCount = 0;
        if(cart == null){
            //产品不在购物车中，需要新添加一条记录
            Cart cartItem = new Cart();
            cartItem.setUserId(userId);
            cartItem.setProductId(productId);
            cartItem.setQuantity(count);
            cartItem.setChecked(Const.Cart.CHECKED);
            rowCount = cartMapper.insert(cartItem);
        }else{
            //产品已经在购物车中，则直接将数量相加
            count = count + cart.getQuantity();
            cart.setQuantity(count);
            rowCount = cartMapper.updateByPrimaryKeySelective(cart);
        }
        if(rowCount <= 0){
            return ServerResponse.createByErrorMessage("购物车添加失败");
        }
        return this.list(userId);
    }


    /**
     * 根据商品库存更新购物车中商品的购买数量（购买数量大于商品库存时要修改购买数量）及总金额等信息
     * @param userId
     * @return
     */
    private CartVO getCartVoLimit(Integer userId){
        CartVO cartVO = new CartVO();

        List<Cart> cartList = cartMapper.selectByUserId(userId);
        List<CartProductVO> cartProductVOList = Lists.newArrayList();
        BigDecimal cartTotalPrice = new BigDecimal("0");

        for(Cart cartItem : cartList){
            CartProductVO cartProductVO = new CartProductVO();
            cartProductVO.setQuantity(cartItem.getQuantity());
            cartProductVO.setProductId(cartItem.getProductId());
            cartProductVO.setUserId(cartItem.getUserId());
            cartProductVO.setId(cartItem.getId());

            Product product = productMapper.selectByPrimaryKey(cartItem.getProductId());
            if(product != null){
                cartProductVO.setProductName(product.getName());
                cartProductVO.setProductSubtitle(product.getSubtitle());
                cartProductVO.setProductMainImage(product.getMainImage());
                cartProductVO.setProductStatus(product.getStatus());
                cartProductVO.setProductPrice(product.getPrice());
                cartProductVO.setProductStock(product.getStock());

                int buyLimitCount = 0;
                if(cartItem.getQuantity() <= product.getStock()){
                    cartProductVO.setLimitQuantity(Const.Cart.LIMIT_NUM_SUCCESS);
                    buyLimitCount = cartItem.getQuantity();
                }else{
                    cartProductVO.setLimitQuantity(Const.Cart.LIMIT_NUM_FAIL);
                    buyLimitCount = product.getStock();
                    Cart cartForQuantity = new Cart();
                    cartForQuantity.setId(cartItem.getId());
                    cartForQuantity.setQuantity(buyLimitCount);
                    cartMapper.updateByPrimaryKeySelective(cartForQuantity);
                }
                cartProductVO.setQuantity(buyLimitCount);
                cartProductVO.setProductChecked(cartItem.getChecked());
                cartProductVO.setProductTotalPrice(BigDecimalUtil.mul(product.getPrice().doubleValue(),cartProductVO.getQuantity()));
                if(cartItem.getChecked() == Const.Cart.CHECKED){
                    cartTotalPrice = BigDecimalUtil.add(cartTotalPrice.doubleValue(),cartProductVO.getProductTotalPrice().doubleValue());
                }
                cartProductVOList.add(cartProductVO);
            }
        }
        cartVO.setCartTotalPrice(cartTotalPrice);
        cartVO.setCartProductVOList(cartProductVOList);
        cartVO.setAllChecked(this.getAllCheckedStatus(userId));
        cartVO.setImageHost(PropertiesUtil.getProperty("ftp.server.http.prefix","ftp://localhost/"));
        return cartVO;

    }


    private boolean getAllCheckedStatus(Integer userId){
        if(userId == null){
            return false;
        }
        return cartMapper.selectCartProductCheckedStatusByUserId(userId) == 0;
    }


    public ServerResponse<CartVO> update(Integer userId,Integer productId,Integer count){
        if(productId == null || count == null){
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(),ResponseCode.ILLEGAL_ARGUMENT.getDesc());
        }

        Cart cart = cartMapper.selectByUserIdAndProductId(userId, productId);
        if(cart != null){
            cart.setQuantity(count);
        }
        cartMapper.updateByPrimaryKeySelective(cart);
        return this.list(userId);
    }

    public ServerResponse<CartVO> delete(Integer userId,String productIds){
        List<String> productIdList = Splitter.on(",").splitToList(productIds);
        if(CollectionUtils.isEmpty(productIdList)){
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(),ResponseCode.ILLEGAL_ARGUMENT.getDesc());
        }
        cartMapper.deleteByUserIdProductIds(userId,productIdList);
        return this.list(userId);
    }


    public ServerResponse<CartVO> list(Integer userId){
        CartVO cartVO = this.getCartVoLimit(userId);
        return ServerResponse.createBySuccess(cartVO);
    }

    public ServerResponse<CartVO> selectOrUnSelect(Integer userId,Integer productId,Integer checked){
        cartMapper.checkedOrUnCheckedProduct(userId,null,checked);
        return this.list(userId);
    }

    public ServerResponse<Integer> getCartProductCount(Integer userId){
        if(userId == null){
            return ServerResponse.createBySuccess(0);
        }
        return ServerResponse.createBySuccess(cartMapper.selectCartProductCount(userId));
    }

}
